//
//  ZBDataManager.m
//  PaoPao
//
//  Created by xzb on 2018/5/7.
//  Copyright © 2018年 paopao. All rights reserved.
//

#import "ZBDataManager.h"

@interface ZBDataManager ()

@property (strong, nonatomic) YTKKeyValueStore *store;

/**
 *  app管理
 */
@property (copy, nonatomic) NSString *appTable;


- (void)setData:(id)data forKey:(NSString *)key intoTable:(NSString *)table;

- (id)dataForKey:(NSString *)key intoTable:(NSString *)table;

- (void)removeObjectForKey:(NSString *)key fromTabel:(NSString *)table;

- (NSArray *)getAllDataFromTable:(NSString *)table;

@end

@implementation ZBDataManager

#pragma mark - base
+ (instancetype)instance
{
    static dispatch_once_t oncePredicate;
    static ZBDataManager *instance;
    dispatch_once(&oncePredicate, ^{
        instance = [[self alloc] init];
        instance.store = [[YTKKeyValueStore alloc] initDBWithName:@"xzbData.db"];
        instance.appTable = @"app_info";
        [instance.store createTableWithName:instance.appTable];
    });
    return instance;
}

- (void)setData:(id)data forKey:(NSString *)key intoTable:(NSString *)table
{
    if ([data isKindOfClass:[NSString class]]) {
        [self.store putString:data withId:key intoTable:table];
        return;
    }
    if ([data isKindOfClass:[NSNumber class]]) {
        [self.store putNumber:data withId:key intoTable:table];
        return;
    }
    [self.store putObject:data withId:key intoTable:table];
    //    eLog(@" <table: %@ > < key: %@> data is error <data : \n%@>",table,key,data);
}

- (id)dataForKey:(NSString *)key  intoTable:(NSString *)table
{
    id obj = [self.store getStringById:key fromTable:table];
    if (!obj) {
        eLog(@" <table: %@ > < key: %@> obj is nil",table,key);
    }
    return obj;
}

- (void)removeObjectForKey:(NSString *)key fromTabel:(NSString *)table
{
    [self.store deleteObjectById:key fromTable:table];
}

- (NSArray *)getAllDataFromTable:(NSString *)table
{
    return  [self.store getAllItemsFromTable:self.appTable];
}

- (void)clear
{
    [self.store clearTable:self.appTable];
}
#pragma mark  - app

- (void)setData:(id)data forKey:(NSString *)key
{
    [self setData:data forKey:key intoTable:self.appTable];
}

- (id)dataForKey:(NSString *)key
{
    return [self dataForKey:key intoTable:self.appTable];
}

- (void)removeObjectForKey:(NSString *)key
{
    [self removeObjectForKey:key fromTabel:self.appTable];
}

- (NSArray *)getAllData
{
    return [self getAllDataFromTable:self.appTable];
}

@end
